package org.example.printexercise;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;

public class PracticeActivityErrorProne extends AppCompatActivity {

    // 统一的布局配置变量
    private static final int WORDS_PER_LINE = 7; // 一行显示7个字
    private static final int HORIZONTAL_MARGIN_DP = 8; // 减小边距为8dp
    private static final int VERTICAL_MARGIN_DP = 3;

    private LinearLayout containerLayout;
    private int screenWidthPx;
    private int screenHeightPx;

    private List<WordItem> wordList;
    private List<EditText> inputEditTexts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_practice_error_prone);

        initViews();
        initData();
        calculateScreenSize();
        setupGrid();
    }

    private void initViews() {
        containerLayout = findViewById(R.id.container_layout);
        inputEditTexts = new ArrayList<>();
    }

    private void initData() {
        wordList = new ArrayList<>();
        wordList.add(new WordItem("听", "tīng"));
        wordList.add(new WordItem("尴尬", "gān gà"));
        wordList.add(new WordItem("脍脍炙人口", "kuài zhì rén kǒu"));
        wordList.add(new WordItem("一个", "yī gè"));
        wordList.add(new WordItem("三个", "sān gè"));
        wordList.add(new WordItem("调", "diào"));
        wordList.add(new WordItem("我的", "wǒ de"));
        wordList.add(new WordItem("世界", "shì jiè"));
        wordList.add(new WordItem("徘徊", "pái huái"));
        wordList.add(new WordItem("打", "dǎ"));
        wordList.add(new WordItem("三", "sān"));
        wordList.add(new WordItem("这是一个歇后语", "zhè shì yī gè xiē hòu yǔ"));
        wordList.add(new WordItem("这是一个故事", "zhè shì yī gè gù shì"));
    }

    private void calculateScreenSize() {
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        screenWidthPx = displayMetrics.widthPixels;
        screenHeightPx = displayMetrics.heightPixels;
    }

    private void setupGrid() {
        containerLayout.removeAllViews();
        inputEditTexts.clear();

        // 获取容器实际可用宽度
        int containerPaddingPx = dpToPx(15); // container_layout的padding
        int availableWidth = screenWidthPx - 2 * containerPaddingPx;

        // 使用浮点数计算避免精度损失
        float columnWidthFloat = (float) availableWidth / WORDS_PER_LINE;

        // 确保列宽至少为1dp，防止过小
        int columnWidth = Math.max(1, Math.round(columnWidthFloat));

        // 创建所有字符的列表
        List<CellItem> allCells = createAllCells();

        // 按行分组并补齐空格
        List<List<CellItem>> rows = groupCellsIntoRows(allCells);

        // 创建网格布局
        createGridLayout(rows, columnWidth);
    }




    private int dpToPx(int dp) {
        float density = getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }

    private List<CellItem> createAllCells() {
        List<CellItem> cells = new ArrayList<>();

        for (int i = 0; i < wordList.size(); i++) {
            WordItem wordItem = wordList.get(i);
            String word = wordItem.word;
            String[] pinyins = wordItem.pinyin.split(" ");

            // 添加词语的每个字符
            for (int j = 0; j < word.length(); j++) {
                CellItem cell = new CellItem();
                cell.type = CellType.CHARACTER;
                cell.character = String.valueOf(word.charAt(j));
                cell.pinyin = (j < pinyins.length) ? pinyins[j] : "";
                cell.wordIndex = i;
                cells.add(cell);
            }

            // 移除空格添加逻辑，不再在词语之间添加空格
        }

        return cells;
    }

    private List<List<CellItem>> groupCellsIntoRows(List<CellItem> allCells) {
        List<List<CellItem>> rows = new ArrayList<>();

        // 先按WORDS_PER_LINE分组，不分割词语
        int index = 0;
        while (index < allCells.size()) {
            List<CellItem> row = new ArrayList<>();
            // 填充实际字符
            int count = 0;
            while (index < allCells.size() && count < WORDS_PER_LINE) {
                row.add(allCells.get(index));
                index++;
                count++;
            }
            // 补齐空格到WORDS_PER_LINE
            while (row.size() < WORDS_PER_LINE) {
                CellItem emptyCell = new CellItem();
                emptyCell.type = CellType.SPACE;
                emptyCell.character = "";
                emptyCell.pinyin = "";
                emptyCell.wordIndex = -1;
                row.add(emptyCell);
            }
            rows.add(row);
        }

        return rows;
    }

    private void createGridLayout(List<List<CellItem>> rows, int columnWidth) {
        for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
            List<CellItem> rowCells = rows.get(rowIndex);

            // 创建行容器
            LinearLayout rowContainer = new LinearLayout(this);
            LinearLayout.LayoutParams containerParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );

            // 设置垂直间距
            containerParams.setMargins(0, dpToPx(VERTICAL_MARGIN_DP), 0, 0);
            rowContainer.setLayoutParams(containerParams);
            rowContainer.setOrientation(LinearLayout.VERTICAL);

            // 创建拼音行
            LinearLayout pinyinRow = createPinyinRow(rowCells, columnWidth);
            // 创建汉字行
            LinearLayout hanziRow = createHanziRow(rowCells, columnWidth);
            // 创建输入行
            LinearLayout inputRow = createInputRow(rowCells, columnWidth, rowIndex);

            rowContainer.addView(pinyinRow);
            rowContainer.addView(hanziRow);
            rowContainer.addView(inputRow);
            containerLayout.addView(rowContainer);
        }
    }

    private LinearLayout createPinyinRow(List<CellItem> rowCells, int columnWidth) {
        LinearLayout rowLayout = new LinearLayout(this);
        rowLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, screenHeightPx / 25));
        rowLayout.setOrientation(LinearLayout.HORIZONTAL);

        for (CellItem cell : rowCells) {
            TextView textView = new TextView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, screenHeightPx / 25);
            textView.setLayoutParams(params);
            textView.setGravity(Gravity.CENTER);
            textView.setBackgroundResource(R.drawable.dashed_border);

            if (cell.type == CellType.SPACE) {
                textView.setText("");
            } else {
                textView.setText(cell.pinyin);
            }

            rowLayout.addView(textView);
        }

        return rowLayout;
    }

    private LinearLayout createHanziRow(List<CellItem> rowCells, int columnWidth) {
        LinearLayout rowLayout = new LinearLayout(this);
        rowLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, (int)(screenHeightPx / 25 * 1.5f)));
        rowLayout.setOrientation(LinearLayout.HORIZONTAL);

        for (CellItem cell : rowCells) {
            TextView textView = new TextView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, (int)(screenHeightPx / 25 * 1.5f));
            textView.setLayoutParams(params);
            textView.setGravity(Gravity.CENTER);
            textView.setBackgroundResource(R.drawable.dashed_border);
            textView.setTextSize(18);

            if (cell.type == CellType.SPACE) {
                textView.setText("");
            } else {
                textView.setText(cell.character);
            }

            rowLayout.addView(textView);
        }

        return rowLayout;
    }

    private LinearLayout createInputRow(List<CellItem> rowCells, int columnWidth, int rowIndex) {
        LinearLayout rowLayout = new LinearLayout(this);
        rowLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, (int)(screenHeightPx / 25 * 1.5f)));
        rowLayout.setOrientation(LinearLayout.HORIZONTAL);

        for (int i = 0; i < rowCells.size(); i++) {
            CellItem cell = rowCells.get(i);
            EditText editText = new EditText(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, (int)(screenHeightPx / 25 * 1.5f));
            editText.setLayoutParams(params);
            editText.setGravity(Gravity.CENTER);
            editText.setInputType(InputType.TYPE_CLASS_TEXT);
            editText.setBackgroundResource(R.drawable.dashed_border);

            if (cell.type == CellType.SPACE) {
                editText.setEnabled(false);
                editText.setHint("");
                editText.setText("");
            } else {
                editText.setTag(new CellTag(rowIndex, i, cell.character, cell.wordIndex));

                // 添加KeyListener处理backspace
                editText.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
                            handleBackspace(editText);
                            return true;
                        }
                        return false;
                    }
                });

                // 添加TextWatcher处理输入
                editText.addTextChangedListener(new InputTextWatcher(editText, inputEditTexts.size()));
                inputEditTexts.add(editText);
            }

            rowLayout.addView(editText);
        }

        return rowLayout;
    }

    private void handleBackspace(EditText currentEditText) {
        int currentIndex = inputEditTexts.indexOf(currentEditText);
        if (currentIndex > 0) {
            // 清空当前输入框
            currentEditText.setText("");

            // 跳转到前一个输入框
            int prevIndex = currentIndex - 1;

            // 跳过空格，找到前一个可编辑的输入框
            while (prevIndex >= 0) {
                EditText prevEditText = inputEditTexts.get(prevIndex);
                if (prevEditText.isEnabled()) {
                    prevEditText.requestFocus();
                    // 选中前一个输入框的文本，方便继续删除
                    prevEditText.setSelection(prevEditText.getText().length());
                    showKeyboard(prevEditText);
                    break;
                }
                prevIndex--;
            }
        }
    }

    // 添加showKeyboard方法
    private void showKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    // 单元格类型
    private enum CellType {
        CHARACTER,
        SPACE
    }

    // 单元格数据类
    private static class CellItem {
        CellType type;
        String character;
        String pinyin;
        int wordIndex; // 属于哪个词语
    }

    // 单元格标签类
    private static class CellTag {
        int rowIndex;
        int cellIndex;
        String expectedChar;
        int wordIndex;

        CellTag(int rowIndex, int cellIndex, String expectedChar, int wordIndex) {
            this.rowIndex = rowIndex;
            this.cellIndex = cellIndex;
            this.expectedChar = expectedChar;
            this.wordIndex = wordIndex;
        }
    }

    // 输入文本监听器
    private class InputTextWatcher implements TextWatcher {
        private EditText editText;
        private int editTextIndex;
        private boolean isSelfChange = false;

        public InputTextWatcher(EditText editText, int editTextIndex) {
            this.editText = editText;
            this.editTextIndex = editTextIndex;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}

        @Override
        public void afterTextChanged(Editable s) {
            if (isSelfChange) return;

            String input = s.toString();
            if (!input.isEmpty()) {
                isSelfChange = true;

                // 只保留最后一个字符
                if (input.length() > 1) {
                    String lastChar = input.substring(input.length() - 1);
                    s.clear();
                    s.append(lastChar);
                }

                // 延迟跳转到下一个输入框（包括空格）
                editText.postDelayed(() -> moveToNextInput(editTextIndex), 100);
                isSelfChange = false;
            }
        }

        private void moveToNextInput(int currentIndex) {
            int nextIndex = currentIndex + 1;

            // 寻找下一个输入框（跳过空格）
            while (nextIndex < inputEditTexts.size()) {
                EditText nextEditText = inputEditTexts.get(nextIndex);
                if (nextEditText.isEnabled()) {
                    nextEditText.requestFocus();
                    showKeyboard(nextEditText);
                    break;
                }
                nextIndex++;
            }

            // 如果是最后一个输入框，隐藏键盘
            if (nextIndex >= inputEditTexts.size()) {
                hideKeyboard();
            }
        }
    }

    // 添加hideKeyboard方法
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm != null && getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    // 单词项数据类
    private static class WordItem {
        String word;
        String pinyin;

        WordItem(String word, String pinyin) {
            this.word = word;
            this.pinyin = pinyin;
        }
    }
}